const {
	Service
} = require('uni-cloud-router')
const uniID = require('uni-id')
const dbHelper = require('db-helper')
const dbUtil = require('db-util')

module.exports = class StoreService extends Service {
	
	async getShorcutMenuList({
		pageNum = 1,
		pageSize = 10,
		city
	}) {
		let result = {
			total: 0,
			list: []
		}
		let dbCmd = this.db.command
		var query = {}
		let storeList = []
		if(city){
			storeList =await this.db.collection('t3ds-store').where({
				'region.city.value' : city
			}).field({
				_id: true
			}).get()
			let storeIds = storeList.data.map(item => {
				return item._id
			})
			if(!storeIds.length){
				return result
			}
			if(storeIds.length){
				query.storeId = dbCmd.in(storeIds)
			}
		}
		if(pageNum == 1) {
			let count = await dbHelper.getCount('t3ds-store-shortcut-menu', {})
			if (!count) {
				return result
			}
			result.total = count
		}
		let res = await this.db.collection("t3ds-store-shortcut-menu").aggregate()
			.match(query)
			.lookup({
				from: "t3ds-mall-goods",
				localField: "goodsId",
				foreignField: "_id",
				as: "goods"
			})
			.lookup({
				from: "t3ds-mall-sku",
				localField: "skuId",
				foreignField: "_id",
				as: "sku"
			})
			.project({
				_id: 1,
				title: 1,
				shareManId: 1,
				goods: "$goods",
				sku: "$sku"
			})
			.skip((pageNum - 1) * pageSize)
			.limit(pageSize)
			.end()
		res.data.forEach(item => {
			if (item.goods.length) {
				item.goodsName = item.goods[0].name
				item.skuName = item.sku[0].name
			}
			delete item.goods
			delete item.sku
		})
		result.list = res.data
		return result
	}

	async getStoreList({
		pageNum = 1,
		pageSize = 10,
		keyword,
		type
	}) {
		// const dbCmd = this.db.command
		// let p1
		// if (type) {
		// 	p1 = {
		// 		type
		// 	}
		// }
		// let p2
		// if (keyword) {
		// 	p2 = dbCmd.or({
		// 		name: new RegExp(keyword)
		// 	}, {
		// 		merchant: {
		// 			merchant_info: {
		// 				name: new RegExp(keyword)
		// 			}
		// 		}
		// 	})
		// }
		// let query = dbCmd.and(p1, p2)
		// if (keyword) {
		// 	query =
		// }
		// let result = {
		// 	total: 0,
		// 	list: []
		// }
		// let countRes = await this.db.collection("t3ds-store").aggregate()
		// 	.lookup({
		// 		from: "uni-id-users",
		// 		localField: "uid",
		// 		foreignField: "_id",
		// 		as: "merchant"
		// 	})
		// 	.unwind("$merchant")
		// 	.match(query)
		// 	.count("total")
		// 	.end()
		// console.log('countRes', countRes)
		// if (!countRes.data.length) {
		// 	return result
		// }
		// result.total = countRes.data[0].total
		// let res = await this.db.collection("t3ds-store").aggregate()
		// 	.lookup({
		// 		from: "uni-id-users",
		// 		localField: "uid",
		// 		foreignField: "_id",
		// 		as: "merchant"
		// 	})
		// 	.unwind("$merchant")
		// 	.match(query)
		// 	.skip((pageNum - 1) * pageSize)
		// 	.limit(pageSize)
		// 	.project({
		// 		name: 1,
		// 		address: 1,
		// 		enabled: 1,
		// 		joinFreePlan: 1,
		// 		phone: 1,
		// 		type: 1,
		// 		owner: "$merchant.username"
		// 	})
		// 	.end()
		// result.list = res.data
		// return result
	}

	async getServiceWithLocation({
		userLocation,
		user,
		where
	}) {
		let res = await this.db.collection("t3ds-store").aggregate().geoNear({
				distanceField: 'distance',
				spherical: true,
				near: new this.db.Geo.Point(Number(userLocation.longitude), Number(userLocation.latitude)),
				query: where
			})
			.lookup({
				from: 't3ds-store-category',
				localField: 'categoryId',
				foreignField: '_id',
				as: 'category'
			})
			.unwind({
				path: "$category"
			})
			.project({
				_id: 1,
				name: 1,
				category: '$category.name',
				address: 1,
				phone: 1,
				photos: 1,
				recommendReason: 1,
				serviceTimes: 1,
				distance: 1,
				serviceContent: 1,
				location: 1
			})
			.end();
		return res.data;
	}

	async getServiceList({
		userLocation,
		token,
		city,
		keyword,
		action = 'all', //全部：all；推荐：recommend；全部除了推荐：allExceptRecommend
		categoryId
	}) {
		try {
			let user
			if (token) {
				let payload = await uniID.checkToken(token)
				if (payload.code === 0) {
					user = payload.userInfo
				}
			}
			let dbCmd = this.db.command
			let where = {
				enabled: true,
				joinFreePlan: true
			}
			switch (action) {
				case 'recommend':
					where.recommend = true
					break
				case 'allExceptRecommend':
					where.recommend = dbCmd.eq(false)
					break
			}
			if (categoryId) {
				where.categoryId = categoryId
			}
			if (city) {
				where['region.city.value'] = city
			}
			if (keyword) {
				where.name = new RegExp(keyword)
			}
			let list
			if (userLocation) {
				list = await this.getServiceWithLocation({
					userLocation,
					user,
					where
				})
			} else {
				let res = await this.db.collection("t3ds-store").aggregate()
					.match(where)
					.lookup({
						from: 't3ds-store-category',
						localField: 'categoryId',
						foreignField: '_id',
						as: 'category'
					})
					.unwind({
						path: "$category"
					})
					.project({
						_id: 1,
						name: 1,
						category: '$category.name',
						address: 1,
						phone: 1,
						photos: 1,
						recommendReason: 1,
						serviceTimes: 1,
						serviceContent: 1,
						location: 1
					})
					.end()
				list = res.data
			}
			let isNormalStoreVip = user && user.vipInfo && user.vipInfo.storeVipCardInfo && user.vipInfo
				.storeVipCardInfo.expirationTime >= Date.now()
			let isSuperVip = isNormalStoreVip && user.vipInfo.storeVipCardInfo.settlementWay === 'time'
			let isMerchantVip = user && user.vipInfo && user.vipInfo.merchantVipCardInfo && user.vipInfo
				.merchantVipCardInfo.expirationTime >= Date.now()
			if (isSuperVip || isMerchantVip) {
				list.forEach(item => {
					item.remainTimes = user.serviceRemainTimes ? user.serviceRemainTimes[item._id] :
						item.serviceTimes
				})
			}
			return {
				code: 200,
				result: list
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}

	async getStoreDetail({
		userLocation,
		token,
		storeId
	}) {
		try {
			let user
			if (token) {
				let payload = await uniID.checkToken(token)
				if (payload.code === 0) {
					user = payload.userInfo
				}
			}
			if (userLocation) {
				let res = await this.db.collection("t3ds-store").aggregate().geoNear({
						distanceField: 'distance',
						spherical: true,
						near: new this.db.Geo.Point(Number(userLocation.longitude), Number(userLocation
							.latitude)),
						query: {
							_id: storeId
						}
					})
					.lookup({
						from: 't3ds-store-category',
						localField: 'categoryId',
						foreignField: '_id',
						as: 'category'
					})
					.unwind({
						path: "$category"
					})
					// .project({
					// 	_id: 1,
					// 	name: 1,
					// 	category: '$category.name',
					// 	address: 1,
					// 	phone: 1,
					// 	photos: 1,
					// 	recommendReason: 1,
					// 	serviceTimes: 1,
					// 	distance: 1,
					// 	serviceContent: 1,
					// 	location: 1
					// })
					.end();
				if (res.data.length) {
					let store = res.data[0]
					let isNormalStoreVip = user && user.vipInfo && user.vipInfo.storeVipCardInfo && user.vipInfo
						.storeVipCardInfo.expirationTime >= Date.now()
					let isSuperVip = isNormalStoreVip && user.vipInfo.storeVipCardInfo.settlementWay === 'time'
					let isMerchantVip = user && user.vipInfo && user.vipInfo.merchantVipCardInfo && user.vipInfo
						.merchantVipCardInfo.expirationTime >= Date.now()
					if (isSuperVip || isMerchantVip) {
						store.remainTimes = user.serviceRemainTimes ? user.serviceRemainTimes[store._id] : store
							.serviceTimes
					}
					return {
						code: 200,
						result: store
					}
				}
				return {
					code: 500,
					msg: "门店不存在"
				}
			} else {
				let store = await dbHelper.getById("t3ds-store", storeId)
				if (!store) {
					return {
						code: 500,
						msg: '门店不存在'
					}
				}
				let category = await dbHelper.getById("t3ds-store-category", store.categoryId)
				store.category = category
				return {
					code: 200,
					result: store
				}
			}
		} catch (e) {
			return {
				code: 500,
				msg: e.message
			}
		}
	}
  
  async screenplaytStore({data, location}) {
    let coll = location === 'room' ? 't3ds-store-room' : 't3ds-store'
        
    // let isUpdateSN = true
    // if (!data.sn) {
    //   isUpdateSN = false
    // }
    // if (data._id) {
    //   let { sn } = await dbHelper.getById(coll, data._id)
    //   if (sn === data.sn) {
    //     isUpdateSN = false
    //   }
    // }
    
    // console.log("isUpdateSN: ",isUpdateSN);
    // if ((data.joinSharePlan && isUpdateSN) || (location === 'room' && isUpdateSN)) {
    //   console.log('注册门禁设备');
    //   // 注册门禁设备
    //   let res = await uniCloud.httpclient.request('https://www.wmj.com.cn/api/reglock', {
    //     method: 'POST',
    //     data: {
    //       appid: "wmj_gvpz8LlGh5R",
    //       appsecret: "1wT4d8WsXD7vsEfUwHd55LlEZ94vuSle",
    //       sn: data.sn
    //     },
    //     contentType: 'form-data',
    //     dataType: 'json'
    //   })
    //   console.log("res: ",res.data);
    //   if (res.data.state == 0) throw res.data
    // }
    try{
      let result = {}
      if (data._id) {
        let id = data._id
        delete data._id
        result = await this.db.collection(coll).doc(id).update(data)
      } else {
        result = await this.db.collection(coll).add(data)
      }
      console.log("result: ",result);
      
      return {
      	code: 200,
      	result
      }
    }catch(e){
      return {
      	code: 500,
      	msg: e
      }
    }
  }
  
  // 获取门禁列表
  async getDoorList(userId, storeId, pageNum = 1, pageSize = 999) {
    const dbCmd = this.db.command
    const $ = dbCmd.aggregate
    
    try{
      let userRes = await dbHelper.getById('uni-id-users', userId)
      let authRes = userRes.role.some(item => ['admin', 'region_mgr'].includes(item))
      
      let data = {}
      if (!authRes) { // 不是超管 或 区管
        let doorOpenRes = await dbHelper.getList('t3ds-door-open', { userId })
        let doorIds = doorOpenRes.map(item => item.doorId)
        data._id = dbCmd.in(doorIds)
      }
      if (storeId) {
        let storeRes = await dbHelper.getById('t3ds-store', storeId)
        if (storeRes.cooperationMode === 'merchant') throw '合作门店无需门禁'
        
        data.storeId = storeId
      }
      let allDoorRes = await dbHelper.getPage('t3ds-door', pageNum, pageSize, data)
      console.log("allDoorRes: ",allDoorRes);
      
      let doorList = []
      for (let i = 0; i < allDoorRes.list.length; i++) {
        let storeRes = await dbHelper.getById('t3ds-store', allDoorRes.list[i].storeId)
        if (storeRes.cooperationMode !== 'merchant') {
          doorList.push(allDoorRes.list[i])
        }
      }
      console.log("doorList: ",doorList);
      
      // 查询设备状态
      for (let i = 0; i < doorList.length; i++) {
        let statusRes = await uniCloud.httpclient.request('https://www.wmj.com.cn/api/lockstatus', {
          method: 'POST',
          data: {
            appid: "wmj_gvpz8LlGh5R",
            appsecret: "1wT4d8WsXD7vsEfUwHd55LlEZ94vuSle",
            sn: doorList[i].sn
          },
          contentType: 'form-data',
          dataType: 'json'
        })
        doorList[i].isOnline = statusRes.data.online
      }
      
      return {
      	code: 200,
      	result: {
          total: doorList.length,
          list: doorList
        }
      }
    }catch(e){
      return {
      	code: 500,
      	msg: e
      }
    }
  }
  
  // 保存门禁
  async saveDoor(storeId, storeName, doorName, sn, _id) {
    const transaction = await this.db.startTransaction()

    try{
      let doorRes = {}
      if (_id) {
        await dbHelper.update("t3ds-door", { storeId, storeName, doorName, sn, _id }, transaction);
        doorRes = await dbHelper.getById("t3ds-door", _id)
      } else {
        await dbHelper.insert("t3ds-door", { storeId, storeName, doorName, sn }, transaction);
      }

      console.log(doorRes.sn, sn);
      if (doorRes.sn !== sn) {
        // 解绑设备
        if (doorRes.sn) {
          let unbindRes = await this.unbindSN(doorRes.sn, storeId)
          console.log("unbindRes: ",unbindRes);
        }
        
        if (sn) {
          // 注册设备
          let regRes = await uniCloud.httpclient.request('https://www.wmj.com.cn/api/reglock', {
            method: 'POST',
            data: {
              appid: "wmj_gvpz8LlGh5R",
              appsecret: "1wT4d8WsXD7vsEfUwHd55LlEZ94vuSle",
              sn
            },
            contentType: 'form-data',
            dataType: 'json'
          })
          console.log("regRes: ",regRes.data);
          if (regRes.data.state === 0) throw regRes.data.state_msg
        }
      }
      
      await transaction.commit()
      return {
      	code: 200,
      	result: '保存成功'
      }
    }catch(e){
      await transaction.rollback()
      return {
      	code: 500,
      	msg: e
      }
    }
  }
  
  // 删除门禁
  async delDoor(doorId, sn) {
    const transaction = await this.db.startTransaction()

    try{
      if (sn) {
        let delRes = await this.unbindSN(sn, doorId)
        console.log("delRes: ",delRes);
        if (delRes.code === 500) throw delRes.msg
        await transaction.collection('t3ds-door-open').where({ doorId }).remove()
      }
      
      await transaction.collection('t3ds-door').doc(doorId).remove()

      await transaction.commit()
      return {
      	code: 200,
      	result: '删除成功'
      }
    }catch(e){
      await transaction.rollback()
      return {
      	code: 500,
      	msg: e
      }
    }
  }
  
  // 解绑门禁设备
  async unbindSN(sn, id) {
    try{
      let res = await uniCloud.httpclient.request('https://www.wmj.com.cn/api/delreglock', {
        method: 'POST',
        data: {
          appid: "wmj_gvpz8LlGh5R",
          appsecret: "1wT4d8WsXD7vsEfUwHd55LlEZ94vuSle",
          sn
        },
        contentType: 'form-data',
        dataType: 'json'
      })
      console.log("res: ",res.data);
      if (res.data.state == 0) throw res.data.state_msg
      
      if (id) {
        // let doorRes = await transaction.collection('t3ds-door').where({ _id: id }).updateAndReturn({ sn: '' })
        await dbHelper.update("t3ds-door", {
          _id: id,
          sn: ''
        })
      }
      
      return {
      	code: 200,
      	result: '解绑成功'
      }
    }catch(e){
      return {
      	code: 500,
      	msg: e
      }
    }
  }
  
  // 打开门禁
  async openDoor(sn) {
    try{
      // const auth = this.ctx.auth;
      // // 超级管理员、区域管理员、店老板、后勤角色
      // let role = ['admin', 'region_mgr', 'boss', 'logistics']
      // let authRes = role.some(item => auth.role.includes(item))
      // if (!authRes)  throw '无开门权限'
      
      
      let statusRes = await uniCloud.httpclient.request('https://www.wmj.com.cn/api/lockstatus', {
        method: 'POST',
        data: {
          appid: "wmj_gvpz8LlGh5R",
          appsecret: "1wT4d8WsXD7vsEfUwHd55LlEZ94vuSle",
          sn
        },
        contentType: 'form-data',
        dataType: 'json'
      })
      console.log("statusRes: ",statusRes.data);
      
      let res = {}
      if (!statusRes.data.online) {
        return {
        	code: 200,
        	result: '设备不在线'
        }
      } else {
        // 开门
        res = await uniCloud.httpclient.request('https://www.wmj.com.cn/api/oplock', {
          method: 'POST',
          data: {
            appid: "wmj_gvpz8LlGh5R",
            appsecret: "1wT4d8WsXD7vsEfUwHd55LlEZ94vuSle",
            sn
          },
          contentType: 'form-data',
          dataType: 'json'
        })
        console.log("res: ",res.data);
        if (res.data.state != 1 && res.data.lock_status != '1') throw res.data.state_msg
      }
      
      return {
      	code: 200,
      	result: res.data.state_msg
      }
    }catch(e){
      return {
      	code: 500,
      	msg: e
      }
    }
  }
  
  async getStoreListByUID(uid) {
	  let list = await dbUtil.getList({
	  	collection: 't3ds-store',
	  	field: {
	  		name: true
	  	},
	  	where: {
	  		uid
	  	}
	  })
	  return list
  }
}
